<template>
  <div>
    <img v-if="imgData != ''" :src="imgData" @click="handlePictureCardPreview" />
    <div :id="'qrid' + qrid" class="qrcode" v-show="imgData == ''" @click="handlePictureCardPreview(imgData)"></div>

    <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
      <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
    </el-dialog>
  </div>
</template>
<script>
import QRCode from "qrcodejs2";
export default {
  name: "QrCodeImg",
  props: ["qrid", "qrContent", "qrWidth", "qrHeight"],
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: "",
      imgData: ""
    };
  },
  watch: {
    //监听二维码内容值的变化，重新生成二维码
    qrContent: function (val) {
      this.qrcode();
    }
  },
  created() { },
  mounted() {
    setTimeout(() => {
      this.qrcode();
    }, 300);
  },
  methods: {
    qrcode() {
      console.log("qrcode", this.qrid, this.qrContent, this.qrTitle);
      this.$nextTick(() => {
        document.getElementById("qrid" + this.qrid).innerHTML = ""; //否则每生成一次，上次的还存在，都会多一个二维码
        //要先生成div再生成二维码，否则Cannot read properties of undefined (reading 'appendChild')
        let qrcode = new QRCode("qrid" + this.qrid, {
          text: this.qrContent + "&" + new Date().getTime(),
          //text为转换为二维码的文本，可以是所有东西：图片、文本、电话、链接等等
          width: this.qrWidth, //生成二维码的宽度
          height: this.qrHeight, //生成二维码的高度
          colorDark: "#333333", // 二维码颜色
          colorLight: "#F8F8FF" //二维码背景颜色
        });


      });
      var canvasobj = document.getElementsByTagName("canvas")[0];
      // 将转换后的img标签插入到html中
      var img = this.CanvasToImage(canvasobj);
      this.imgData = img.src;
    },
    CanvasToImage(canvas) {
      //从canvas中提取图片image，新建image对象
      return new Image();;
    },
    // 预览
    handlePictureCardPreview(imgData) {
      // this.dialogImageUrl =imgData;
      // this.dialogVisible = true;
    },
  }
};
</script>
